import {
  formatDate
} from '../../utils/util';

const startSwipeLength = 20;
const maxSwipeLength = 100;
Component({
  properties: {
    news: {
      type: Object,
      observer: function (newVal, oldVal, chengedPath) {
        if (this.data.status === 'removed') {
          const timestampString = formatDate(new Date(this.data.news.timestamp));
          this.setData({
            status: 'reloading',
            timestampString: timestampString,
            currentLength: -this.data.newsInnerContainerWidth,
            notInterestedOpacity: 0,
            contentLayerOpacity: 0,
          }, this.reload);
        }
      }
    },
  },
  data: {
    timestampString: null,

    newsInnerContainerWidth: null,

    status: 'default', //default preSwiping swiping recovering waiting removing removed reloading
    startPosition: null,
    startTime: null,
    startLength: null,
    currentPosition: null,
    curentTime: null,
    currentLength: 0,

    recoveringTimer: null,
    removingTimer: null,
    reloadingTimer: null,

    notInterestedOpacity: 0,
    contentLayerOpacity: 1,
  },
  created: function (options) {
    // console.log('newCard', 'created');
    // console.log(arguments);
    // console.log(this.data);
    // 组件生命周期函数，在组件实例进入页面节点树时执行，注意此时不能调用 setData
  },
  attached: function () {
    // console.log('newCard', 'attached');
    // 组件生命周期函数，在组件实例进入页面节点树时执行
  },
  ready: function () {
    // console.log('newCard', 'ready');
    const timestampString = formatDate(new Date(this.data.news.timestamp));
    this.setData({
      timestampString: timestampString
    });
    const _this = this;
    const wxQurey = wx.createSelectorQuery().in(this);
    wxQurey.select('.news-card').boundingClientRect();
    wxQurey.exec(res => {
      _this.setData({
        newsInnerContainerWidth: res[0].width
      })
    });
    // 组件生命周期函数，在组件布局完成后执行，此时可以获取节点信息（使用 SelectorQuery ）
  },
  moved: function () {
    // console.log('newCard', 'moved');
    // 组件生命周期函数，在组件实例被移动到节点树另一个位置时执行
  },
  detached: function () {
    // console.log('newCard', 'detached');
    // 组件生命周期函数，在组件实例被从页面节点树移除时执行
  },
  methods: {
    onNewsTapped: function (e) {
      if (this.data.status === 'waiting') {
        this.recover();
      } else if (this.data.status === 'default') {
        this.triggerEvent('news-tapped', this.data.news);
      }
      // console.log('news tapped');
    },
    swipeStart: function (e) {
      const touch = e.touches[0];
      const x = touch.clientX;
      const y = touch.clientY;
      switch (this.data.status) {
        case 'default':
          {
            this.setData({
              status: 'preSwiping',
              startPosition: x,
              startTime: new Date(),
              startLength: 0,
              currentPosition: x,
              curentTime: new Date(),
              currentLength: 0,
            });
            return;
          }
        case 'waiting':
          {
            this.setData({
              status: 'swiping',
              startPosition: x,
              startTime: new Date(),
              startLength: this.data.currentLength,
              currentPosition: x,
              curentTime: new Date(),
              currentLength: this.data.currentLength,
            });
            return;
          }
        case 'recovering':
          {
            if (this.data.recoveringTimer !== null) {
              clearTimeout(this.data.recoveringTimer);
            }
            this.setData({
              status: 'swiping',
              startPosition: x,
              startTime: new Date(),
              startLength: this.data.currentLength,
              currentPosition: x,
              curentTime: new Date(),
              currentLength: this.data.currentLength,
              recoveringTimer: null,
              notInterestedOpacity: this.data.currentLength / maxSwipeLength,
            });
            return;
          }
      }
    },
    swiping: function (e) {
      const touch = e.touches[0];
      const x = touch.clientX;
      switch (this.data.status) {
        case 'preSwiping':
          {
            const currentLength = this.data.startPosition - x + this.data.startLength;
            if (currentLength > startSwipeLength) {
              this.setData({
                status: 'swiping',
                startPosition: x,
                startTime: new Date(),
                startLength: 0,
                currentPosition: x,
                curentTime: new Date(),
                currentLength: 0,
              });
            } else {
              this.setData({
                status: 'preSwiping',
                // startPosition: x,
                // startTime: new Date(),
                // startLength: 0,
                currentPosition: x,
                curentTime: new Date(),
                currentLength: 0,
              });
            }
            return;
          }
        case 'swiping':
          {
            const currentLength = this.data.startPosition - x + this.data.startLength;
            if (currentLength < 0) {
              this.setData({
                status: 'swiping',
                startPosition: x,
                startTime: new Date(),
                startLength: 0,
                currentPosition: x,
                curentTime: new Date(),
                currentLength: 0,
              });
            } else {
              const finalCurrentLength = Math.min(currentLength, maxSwipeLength);
              this.setData({
                // status: 'swiping',
                // startPosition: x,
                // startTime: new Date(),
                // startLength: 0,
                currentPosition: x,
                curentTime: new Date(),
                currentLength: finalCurrentLength,

                notInterestedOpacity: finalCurrentLength / maxSwipeLength,
                // contentLayerOpacity: 1,
              });
            }
            return;
          }
      }
    },
    swipeOver: function (e) {
      const touch = e.changedTouches[0];
      const x = touch.clientX;
      switch (this.data.status) {
        case 'preSwiping':
          {
            this.setData({
              status: 'default',
              startPosition: null,
              startTime: null,
              startLength: null,
              currentPosition: null,
              curentTime: null,
              currentLength: null,
            });
            return;
          }
        case 'swiping':
          {
            const currentLength = this.data.startPosition - x + this.data.startLength;
            if (currentLength < 0) {
              this.setData({
                status: 'default',
                startPosition: null,
                startTime: null,
                startLength: null,
                currentPosition: null,
                curentTime: null,
                currentLength: 0,
              });
            } else if (currentLength < maxSwipeLength) {
              const _this = this;
              this.setData({
                status: 'recovering',
                startPosition: null,
                startTime: null,
                startLength: null,
                currentPosition: null,
                curentTime: null,
                currentLength: currentLength,

                notInterestedOpacity: currentLength / maxSwipeLength,
                // contentLayerOpacity: 1,
              }, () => {
                _this.recover();
              });
            } else {
              this.setData({
                status: 'waiting',
                startPosition: null,
                startTime: null,
                startLength: null,
                currentPosition: null,
                curentTime: null,
                currentLength: maxSwipeLength,

                notInterestedOpacity: 1,
                // contentLayerOpacity: 1,
              });
            }
            return;
          }
      }
    },
    notInterestedTapped: function (e) {
      if (this.data.status === 'waiting') {
        this.remove();
      }
    },
    recover: function () {
      this._recover(this);
    },
    _recover: function (that) {
      let currentLength = that.data.currentLength;
      currentLength *= 0.9;
      currentLength = parseInt(currentLength);
      if (currentLength < 3) {
        currentLength = 0;
      } else if (currentLength === that.data.currentLength) {
        currentLength = that.data.currentLength - 1;
      }
      let timer = null;
      if (currentLength !== 0) {
        timer = setTimeout(that._recover, 10, that);
        that.setData({
          currentLength: currentLength,
          recoveringTimer: timer,
          notInterestedOpacity: currentLength / maxSwipeLength,
          // contentLayerOpacity: 1,
        });
      } else {
        that.setData({
          status: 'default',
          currentLength: null,
          recoveringTimer: null,
          notInterestedOpacity: 0,
          // contentLayerOpacity: 1,
        });
      }
    },
    remove: function () {
      this._remove(this);
    },
    _remove: function (that) {
      let currentLength = that.data.currentLength;
      currentLength += 5;
      currentLength = parseInt(currentLength);
      if (currentLength >= that.data.newsInnerContainerWidth) {
        currentLength = that.data.newsInnerContainerWidth;
      }
      let timer = null;
      if (currentLength !== that.data.newsInnerContainerWidth) {
        timer = setTimeout(that._remove, 10, that);
        that.setData({
          currentLength: currentLength,
          removingTimer: timer,
          notInterestedOpacity: 0,
          contentLayerOpacity: 1 - currentLength / that.data.newsInnerContainerWidth,
        });
      } else {
        that.setData({
          status: 'removed',
          currentLength: null,
          removingTimer: null,
          notInterestedOpacity: 0,
          contentLayerOpacity: 0,
        }, () => {
          that.triggerEvent('news-removed', {
            news: that.data.news
          })
        });
      }
    },
    reload: function () {
      this._reload(this);
    },
    _reload: function (that) {
      let currentLength = that.data.currentLength;
      currentLength += 10;
      currentLength = parseInt(currentLength);
      if (currentLength >= 0) {
        currentLength = 0;
      }
      let timer = null;
      if (currentLength !== 0) {
        timer = setTimeout(that._reload, 10, that);
        that.setData({
          currentLength: currentLength,
          reloadingTimer: timer,
          notInterestedOpacity: 0,
          contentLayerOpacity: 1 + currentLength / that.data.newsInnerContainerWidth,
        });
      } else {
        that.setData({
          status: 'default',
          currentLength: null,
          reloadingTimer: null,
          notInterestedOpacity: 0,
          contentLayerOpacity: 1,
        });
      }
    }
  }
})